package com.sjy.mvvmdemo.roomdb

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.sjy.mvvmdemo.R
import com.sjy.mvvmdemo.databinding.ItemSecondBinding
import com.sjy.mvvmdemo.roomdb.db.UserEntity

/**
 * 没有绑定room的普通RecyclerView
 */
class SecondAdapter(private val clickListener: (UserEntity) -> Unit) :
    RecyclerView.Adapter<SecondAdapter.MyHolder>() {

    var mList = ArrayList<UserEntity>()
    fun updateData(items: List<UserEntity>) {
        mList.clear()
        mList.addAll(items)
        notifyDataSetChanged()
    }

    //编写顺序(1)
    class MyHolder(private val binding: ItemSecondBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(mUser: UserEntity, clickListener: (UserEntity) -> Unit) {
            //赋值
            binding.apply {
                binding.tvUser.text = mUser.user
                binding.tvPs.text = mUser.pass
            }
        }
    }

    //编写顺序(2)
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        //item_second.xml的binding是ItemSecondBinding
        val binding =
            DataBindingUtil.inflate<ItemSecondBinding>(
                layoutInflater,
                R.layout.item_second,
                parent,
                false
            )
        return MyHolder(binding)
    }

    //编写顺序(3)
    override fun getItemCount(): Int {
        return mList!!.size
    }

    //编写顺序(4)
    override fun onBindViewHolder(holder: MyHolder, position: Int) {
        //绑定数据
        holder.apply {
            bind(mList!![position], clickListener)
        }
    }
}


